package com.wangp.mywrite.coding;

import java.util.ArrayList;
import java.util.List;

/***
 * @author wangpeng
 * @since 2022-03-04  9:45
 *
 * 各位相加
 */
public class AddDigits {

    public static void main(String[] args) {
        new AddDigits().addDigits(101);
        System.out.println(new AddDigits().addDigits2(101));
    }


    public int addDigits(int num) {

        if (num / 10 == 0) {
            return num;
        }
        return sum(num);
    }

    public int sum(int num) {
        List<Integer> digits = new ArrayList<>();
        setDigits(num, digits);
        int res = sum(digits);
        if (res / 10 == 0) {
            return res;
        } else {
            return sum(res);
        }
    }

    private int sum(List<Integer> digits) {
        int sum = 0;
        for (Integer digit : digits) {
            sum += digit;
        }
        return sum;
    }

    private void setDigits(int num, List<Integer> digits) {
        while (num != 0) {
            int i = num % 10;
            digits.add(i);
            num = num / 10;
        }
    }


    public int addDigits2(int num) {

        while (num >= 10) {
            int sum = 0;
            while (num != 0) {
                sum += num % 10;
                num /= 10;
            }
            num = sum;
        }
        return num;
    }
}
